package com.xd.common.security.config;

import cn.hutool.core.collection.CollUtil;
import com.xd.common.utils.PathMatchingUtil;
import com.xd.user.api.feign.PermissionFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * 重写security权限控制
 * @author hbx
 */
@Component
@Slf4j
public class SecurityAccessDecisionManager implements AccessDecisionManager {

    @Autowired
    private PermissionFeign permissionFeign;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void decide(Authentication authentication, Object object,
                       Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        String requestUrl = ((FilterInvocation) object).getRequest()
                .getRequestURI();
        List<String> strings = permissionFeign.selectPermissionPaths();
        //当前请求包含于需拦截请求中,拦截该请求,并判断用户是否拥有改权限
        if (PathMatchingUtil.matches(requestUrl, strings)) {
            log.warn("当前路径不在权限拦截列表,路径:{}", requestUrl);
            return;
        }
        // 当前用户所具有的权限
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        List<String> collect = authorities.stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());
        //跳过拦截
        if (!PathMatchingUtil.matches(requestUrl, collect)) {
            log.warn("用户拥有该路径权限,放开拦截,路径:{}", requestUrl);
            return;
        }
        throw new AccessDeniedException("无访问权限");
    }

    /**
     * 复制默认方法，使得@PreAuthorize("hasRole('ROLE_ADMIN')") 可用
     */
    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }


}
